<template>
  <div class="CustomerRecord">
    <div class="dynamicTop">
      <Title v-if="titleShow" title="客户动态" :iconShow="true">
        <template slot="icon">
          <i
            class="V7_iconfont V7_iconV7tubiao_kehudongtai"
            style="color: #008bee; font-size: 14px; margin-right: 5px"
          ></i>
        </template>
      </Title>
      <div style="display: flex; align-items: center">
        <el-select
          v-model="formData.category"
          multiple
          placeholder="全部"
          :collapse-tags="true"
          clearable
          @change="searchDy"
        >
          <el-option
            v-for="item in records"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="formData.datetime"
          style="margin-left: 10px; width: 320px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          :clearable="false"
          end-placeholder="结束日期"
          @change="searchDy"
        >
        </el-date-picker>
        <DySearch
          ref="dySearch"
          @searchDy="searchDy"
          :stateOptions="stateOptions"
          :busCategory="busCategory"
        />
      </div>
    </div>
    <Dynamic
      ref="Dynamic"
      style="height: 100%"
      :data="dynamicData"
      :moreShow="moreShow"
      @loadMore="loadMore"
      @updateDynamic="searchDy"
    ></Dynamic>
  </div>
</template>

<script lang="ts">
/**
 * 客户详情客户动态轨迹
 */
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import Title from '../common/title.vue'
import Dynamic from '../common/dynamic.vue'
import { commonAction, getCurrentDateTime, getFormatDateTime } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { TagModule } from '@/store/modules/tag'
import DySearch from './dySearch.vue'
const today = () => {
  const date = getCurrentDateTime().split(' ')[0]
  const lastDate = new Date(date + ' 00:00:00').getTime() - (7 * 24 * 60 * 60 * 1000)
  const nextDate = new Date(date + ' 23:59:59').getTime()
  return [getFormatDateTime(new Date(lastDate), ''), getFormatDateTime(new Date(nextDate), '')]
}
@Component({
  name: 'CustomerRecord',
  components: {
    Title,
    Dynamic,
    DySearch
  }
})
export default class CustomerRecord extends Vue {
  @Ref() private dySearch
  @Prop() private customerId
  @Prop() private busCategory
  @Prop({ default: () => true }) private titleShow
  private dynamicData = []

  private formData: any = {
    datetime: today(),
    category: []
  }

  private pageData: any = {
    page: 1,
    limit: 10,
    total: 0
  }

  private moreShow: boolean = false

  private records: any = [
    {
      label: '工单记录',
      value: 'workorder'
    },
    {
      label: '通话记录',
      value: 'call'
    },
    {
      label: '会话记录',
      value: 'webchat'
    },
    {
      label: '跟进记录',
      value: 'follow'
    }
  ]

  private setData () {
    this.formData.category = []
    this.formData.datetime = today()
  }

  public clearSearchData () { // 清空搜索条件
    this.setData()
    this.$nextTick(() => {
      this.dySearch.clearDynamicSearch()
    })
  }

  private stateOptions: object[] = [ // 呼叫类型
    { name: '呼入', _id: 'incoming' },
    { name: '外呼', _id: 'dialout' },
    { name: '转移', _id: 'transfer' },
    { name: '咨询转移', _id: 'consultTransfer' },
    { name: '双向回呼', _id: 'webcall' },
    { name: '预览外呼', _id: 'previewDialout' },
    { name: '自动外呼', _id: 'autoDialout' }
  ]

  private getTitle (type: any) {
    switch (type) {
      case 'follow':
        return '跟进记录'
      case 'workorder':
        return '工单记录'
      case 'webchat':
        return '会话记录'
      case 'call':
        return '通话记录'
    }
  }

  private getAgentName (id: any) {
    const agent = (CommonModule as any).publicCache.userListObj[id]
    if (agent) {
      return `${agent.agentName} 【${agent.agentNumber}】`
    }
    return ''
  }

  private getQueueName (id: any) {
    const quenes = (CommonModule as any).publicCache.queueListObj[id]
    if (quenes) {
      return quenes.name
    }
    return ''
  }

  private getWeChatTags (id) {
    const chatTags = (CommonModule as any).publicCache.sessionTagsTreeObj[id]
    if (chatTags && chatTags.name) {
      return chatTags
    }
    return {}
  }

  private getWorkStatus (code: any) {
    switch (code) {
      case 0:
        return '未提交'
      case 10:
        return '待领取'
      case 20:
        return ' 待处理'
      case 30:
        return '完成'
      case 40:
        return '终止'
    }
  }

  private getAccessIdOpt (accessId: any) {
    const accessObj: any = {}
    CommonModule.publicCache.channelList.map((item: any) => {
      accessObj[item.accessId] = item
    })
    if (accessObj[accessId]) {
      return accessObj[accessId].name
    }
    return ''
  }

  public searchDy (form: any) {
    this.pageData.page = 1
    this.dynamicData = []
    this.getDynamic(form)
  }

  private getDynamic (form?: any) {
    const { page, limit } = this.pageData
    if (!this.formData.datetime) {
      this.formData.datetime = []
    }
    const params = {
      url: '/server-crm/action/customer/dynamics/query',
      method: 'POST',
      data: {
        customerId: this.customerId,
        page,
        limit,
        datetime: this.formData.datetime,
        category: this.formData.category,
        ...form
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        if (res.data.list && res.data.list.length) {
          res.data.list.map(async item => {
            item.title = this.getTitle(item.category)
            if (item.category === 'follow') { // 跟进记录
              item.agent = this.getAgentName(item.content.agentId)
            } else if (item.category === 'workorder') { // 工单
              if (item.content.createUser) {
                if (this.getAgentName(item.content.createUser)) {
                  item.creater = this.getAgentName(item.content.createUser)
                } else {
                  item.creater = ''
                  // 座席中没有 匹配客户
                  const resp = await commonAction({
                    url: `/server-crm/action/customer/${item.content.createUser}`,
                    method: 'GET'
                  })
                  if (resp.success && resp.data) {
                    item.creater = resp.data.name
                  }
                }
              }
              item.master = this.getAgentName(item.content.master)
              item.statusNum = item.content.status
              // item.orderStatus = this.getWorkStatus(item.content.status)
            } else if (item.category === 'webchat') {
              item.agent = this.getAgentName(item.content.agentId)
              item.queueNumber = this.getQueueName(item.content.queueNumber)
              item.accessName = this.getAccessIdOpt(item.content.accessId)
              // 处理标签
              if (item.content.tags) {
                const tags = item.content.tags.map(tagId => {
                  return this.getWeChatTags(tagId)
                })
                item.tags = tags.filter(v => v.name)
              }
            } else if (item.category === 'call') {
              item.queueNumber = this.getQueueName(item.content.queueNumber)
              item.agent = this.getAgentName(item.content.agentId)
              if (item.content.tags) {
                const tags: any = []
                item.content.tags.map(tagId => {
                  if (TagModule.tagMap.get(tagId)) {
                    tags.push(TagModule.tagMap.get(tagId))
                  }
                })
                item.tags = tags
              }
            }
          })
        }
        this.dynamicData = this.dynamicData.concat(res.data.list)
        this.pageData.total = res.data.count
        if (this.pageData.total > limit * page) {
          this.moreShow = true
        } else {
          this.moreShow = false
        }
      }
    })
  }

  private loadMore () {
    const { total, page, limit } = this.pageData
    if (total > page * limit) {
      this.pageData.page++
      this.getDynamic()
    }
  }
}
</script>

<style lang="stylus" scoped>
.el-select
  width 170px
.CustomerRecord
  position relative
  /deep/ .el-range__icon, .el-range__close-icon, el-range-separator
    line-height 24px
  /deep/ .el-range__close-icon
    line-height 24px
  /deep/ .el-range-separator
    line-height 24px
  .dynamicTop
    height 62px
    display flex
    align-items center
    justify-content space-between
    border-bottom 1px solid #E7E9ED
</style>
